// ==========================================
// 资产盘点与报废管理API - 第三阶段
// ==========================================

// ========== 盘点管理 ==========

// 创建盘点计划（管理员）
app.post('/api/admin/inventory/create', async (req, res) => {
    try {
        const { title, startDate, endDate, scope, scopeValue, adminKey } = req.body;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        if (!title || !startDate || !endDate) {
            return res.json({ code: 1001, success: false, message: '缺少必要参数' });
        }

        // 计算应盘数量
        let countSql = 'SELECT COUNT(*) as count FROM assets WHERE 1=1';
        const countParams = [];

        if (scope === 'lab' && scopeValue) {
            countSql += ' AND lab_id = ?';
            countParams.push(scopeValue);
        } else if (scope === 'category' && scopeValue) {
            countSql += ' AND category_id = ?';
            countParams.push(scopeValue);
        }

        const [countResult] = await pool.execute(countSql, countParams);
        const totalCount = countResult[0].count;

        const [result] = await pool.execute(
            `INSERT INTO asset_inventory (title, start_date, end_date, scope, scope_value, total_count, creator_openid)
             VALUES (?, ?, ?, ?, ?, ?, ?)`,
            [title, startDate, endDate, scope, scopeValue, totalCount, 'admin']
        );

        res.json({
            code: 0,
            success: true,
            message: '创建成功',
            data: { inventoryId: result.insertId }
        });
    } catch (error) {
        console.error('创建盘点失败:', error);
        res.json({ code: 9999, success: false, message: '创建失败' });
    }
});

// 获取盘点列表
app.get('/api/inventory/list', async (req, res) => {
    try {
        const { status, page = 1, pageSize = 20 } = req.query;

        let sql = 'SELECT * FROM asset_inventory WHERE 1=1';
        const params = [];

        if (status) {
            sql += ' AND status = ?';
            params.push(status);
        }

        sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
        params.push(parseInt(pageSize), (parseInt(page) - 1) * parseInt(pageSize));

        const [rows] = await pool.execute(sql, params);

        res.json({ code: 0, success: true, data: { list: rows } });
    } catch (error) {
        console.error('获取盘点列表失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// 扫码盘点
app.post('/api/inventory/check', async (req, res) => {
    const connection = await pool.getConnection();

    try {
        await connection.beginTransaction();

        const { inventoryId, assetCode, result, checkerOpenid, checkerName } = req.body;

        if (!inventoryId || !assetCode) {
            return res.json({ code: 1001, success: false, message: '缺少必要参数' });
        }

        // 获取资产信息
        const [assets] = await connection.execute(
            'SELECT * FROM assets WHERE asset_code = ?',
            [assetCode]
        );

        if (assets.length === 0) {
            await connection.rollback();
            return res.json({ code: 2001, success: false, message: '资产不存在' });
        }

        const asset = assets[0];

        // 检查是否已盘点
        const [existing] = await connection.execute(
            'SELECT * FROM asset_inventory_detail WHERE inventory_id = ? AND asset_id = ?',
            [inventoryId, asset.id]
        );

        if (existing.length > 0) {
            await connection.rollback();
            return res.json({ code: 2002, success: false, message: '该资产已盘点' });
        }

        // 插入盘点明细
        await connection.execute(
            `INSERT INTO asset_inventory_detail (inventory_id, asset_id, asset_code, result, checker_openid, checker_name, check_time)
             VALUES (?, ?, ?, ?, ?, ?, NOW())`,
            [inventoryId, asset.id, assetCode, result, checkerOpenid, checkerName]
        );

        // 更新盘点统计
        const updateFields = ['checked_count = checked_count + 1'];
        if (result === 'normal') updateFields.push('normal_count = normal_count + 1');
        if (result === 'surplus') updateFields.push('surplus_count = surplus_count + 1');
        if (result === 'loss') updateFields.push('loss_count = loss_count + 1');

        await connection.execute(
            `UPDATE asset_inventory SET ${updateFields.join(', ')} WHERE id = ?`,
            [inventoryId]
        );

        await connection.commit();

        res.json({ code: 0, success: true, message: '盘点成功', data: { assetName: asset.name } });
    } catch (error) {
        await connection.rollback();
        console.error('盘点失败:', error);
        res.json({ code: 9999, success: false, message: '盘点失败' });
    } finally {
        connection.release();
    }
});

// 获取盘点报告
app.get('/api/inventory/report/:id', async (req, res) => {
    try {
        const { id } = req.params;

        // 获取盘点主信息
        const [inventory] = await pool.execute(
            'SELECT * FROM asset_inventory WHERE id = ?',
            [id]
        );

        if (inventory.length === 0) {
            return res.json({ code: 2001, success: false, message: '盘点不存在' });
        }

        // 获取盘点明细
        const [details] = await pool.execute(
            `SELECT d.*, a.name as asset_name, a.brand, a.model
             FROM asset_inventory_detail d
             LEFT JOIN assets a ON d.asset_id = a.id
             WHERE d.inventory_id = ?
             ORDER BY d.check_time DESC`,
            [id]
        );

        res.json({
            code: 0,
            success: true,
            data: {
                inventory: inventory[0],
                details: details
            }
        });
    } catch (error) {
        console.error('获取盘点报告失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// ========== 报废管理 ==========

// 申请报废
app.post('/api/asset/disposal/apply', async (req, res) => {
    try {
        const { assetId, reason, images, applicantOpenid, applicantName } = req.body;

        if (!assetId || !reason) {
            return res.json({ code: 1001, success: false, message: '缺少必要参数' });
        }

        // 检查资产是否存在
        const [assets] = await pool.execute(
            'SELECT * FROM assets WHERE id = ?',
            [assetId]
        );

        if (assets.length === 0) {
            return res.json({ code: 2001, success: false, message: '资产不存在' });
        }

        // 插入报废申请
        const [result] = await pool.execute(
            `INSERT INTO asset_disposal (asset_id, applicant_openid, applicant_name, reason, images)
             VALUES (?, ?, ?, ?, ?)`,
            [assetId, applicantOpenid, applicantName, reason, JSON.stringify(images || [])]
        );

        res.json({
            code: 0,
            success: true,
            message: '申请成功，等待审批',
            data: { disposalId: result.insertId }
        });
    } catch (error) {
        console.error('申请报废失败:', error);
        res.json({ code: 9999, success: false, message: '申请失败' });
    }
});

// 获取报废列表
app.get('/api/asset/disposal/list', async (req, res) => {
    try {
        const { status, applicant, page = 1, pageSize = 20 } = req.query;

        let sql = `SELECT d.*, a.asset_code, a.name as asset_name
                   FROM asset_disposal d
                   LEFT JOIN assets a ON d.asset_id = a.id
                   WHERE 1=1`;
        const params = [];

        if (status) {
            sql += ' AND d.status = ?';
            params.push(status);
        }
        if (applicant) {
            sql += ' AND d.applicant_openid = ?';
            params.push(applicant);
        }

        sql += ' ORDER BY d.created_at DESC LIMIT ? OFFSET ?';
        params.push(parseInt(pageSize), (parseInt(page) - 1) * parseInt(pageSize));

        const [rows] = await pool.execute(sql, params);

        res.json({ code: 0, success: true, data: { list: rows } });
    } catch (error) {
        console.error('获取报废列表失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// 审批报废（管理员）
app.post('/api/admin/asset/disposal/approve', async (req, res) => {
    const connection = await pool.getConnection();

    try {
        await connection.beginTransaction();

        const { disposalId, approve, rejectReason, approverOpenid, approverName, adminKey } = req.body;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        if (!disposalId || approve === undefined) {
            return res.json({ code: 1001, success: false, message: '缺少必要参数' });
        }

        // 获取报废记录
        const [disposals] = await connection.execute(
            'SELECT * FROM asset_disposal WHERE id = ? AND status = "pending"',
            [disposalId]
        );

        if (disposals.length === 0) {
            await connection.rollback();
            return res.json({ code: 2001, success: false, message: '报废记录不存在或已处理' });
        }

        const disposal = disposals[0];
        const newStatus = approve ? 'approved' : 'rejected';

        // 更新报废记录
        await connection.execute(
            `UPDATE asset_disposal 
             SET status = ?, approver_openid = ?, approver_name = ?, approve_time = NOW(), reject_reason = ?, disposal_date = ?
             WHERE id = ?`,
            [newStatus, approverOpenid, approverName, rejectReason, approve ? new Date().toISOString().split('T')[0] : null, disposalId]
        );

        // 如果批准，更新资产状态为已报废
        if (approve) {
            await connection.execute(
                'UPDATE assets SET status = "scrapped" WHERE id = ?',
                [disposal.asset_id]
            );
        }

        await connection.commit();

        res.json({
            code: 0,
            success: true,
            message: approve ? '已批准报废' : '已拒绝报废'
        });
    } catch (error) {
        await connection.rollback();
        console.error('审批报废失败:', error);
        res.json({ code: 9999, success: false, message: '审批失败' });
    } finally {
        connection.release();
    }
});
